//
//  ChooseTypeViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "ChooseTypeViewController.h"
#import "HeadCollectionReusableView.h"
#import "ChooseTypeCollectionViewCell.h"
#import "TypeTitleModel.h"
#import "FooterCollectionReusableView.h"
#import "ChooseTypeMod.h"

#define HEADBACKVIEW 135


@interface ChooseTypeViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *chooseCollectionV;
@property (nonatomic, retain) UILabel *infoL;
@property (nonatomic, retain) UIButton *footerBtn;

//@property (nonatomic, retain) ChooseTypeCollectionViewCell *cell;
@property (nonatomic, assign) BOOL isOn; // 是否选中

@property (nonatomic, retain) NSMutableDictionary *chooseDic;
@property (nonatomic, retain) NSMutableArray *sortKeyArr;

@property (nonatomic, retain) NSMutableArray *keyValueArr;

@property (nonatomic, retain) NSMutableArray *isSelectArr;
@end

@implementation ChooseTypeViewController
- (void)dealloc
{
    [_chooseCollectionV release];
    [_infoL release];
    [_footerBtn release];
    [_chooseDic release];
    [_sortKeyArr release];
    [_keyValueArr release];
    [_isSelectArr release];
    [super dealloc];
}
+ (instancetype)shareChooseTypeViewController
{
    static ChooseTypeViewController *chooseType = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        chooseType = [[ChooseTypeViewController alloc] init];
    });
    return chooseType;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getUpdateWithURL];
    self.isOn = NO;
    self.chooseDic = [NSMutableDictionary dictionary];
    self.sortKeyArr = [NSMutableArray array];

    self.isSelectArr = [NSMutableArray array];
    self.keyValueArr = [NSMutableArray array];

    // 创建头部区域
    [self createHeadView];
    
    // 底部button
    self.footerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.footerBtn setTitle:@"完成" forState:UIControlStateNormal];
    [self.footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.footerBtn.backgroundColor = [UIColor colorWithRed:0.95 green:0.58 blue:0.14 alpha:1];
    self.footerBtn.titleLabel.font = [UIFont systemFontOfSize:15.5f];
    self.footerBtn.frame = CGRectMake(0, SCREEN_HEIGHT - 44, SCREEN_WIDTH, 44);
    [self.footerBtn addTarget:self action:@selector(footerBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.footerBtn];
    
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置每个item(cell)的大小
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH / 4.f - 18 * AUTOSCREEN_WIDTH, 35.f * AUTOSCREEN_HEIGHT);
    // 设置最小行间距
    flowLayout.minimumLineSpacing = 10 * AUTOSCREEN_HEIGHT;
    // 设置最小列间距
    flowLayout.minimumInteritemSpacing = 10 * AUTOSCREEN_WIDTH;
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * AUTOSCREEN_HEIGHT, 10 * AUTOSCREEN_WIDTH, 10 * AUTOSCREEN_HEIGHT, 10 * AUTOSCREEN_WIDTH);
    // 设置头部区域的大小
    flowLayout.headerReferenceSize = CGSizeMake(0, 40 * AUTOSCREEN_HEIGHT);
    
    // 滚动方向
//    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.chooseCollectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEADBACKVIEW, SCREEN_WIDTH, SCREEN_HEIGHT - HEADBACKVIEW - self.footerBtn.frame.size.height) collectionViewLayout:flowLayout];
    self.chooseCollectionV.delegate = self;
    self.chooseCollectionV.dataSource = self;

    // 隐藏滑动条
    self.chooseCollectionV.showsHorizontalScrollIndicator = NO;
    
    // 注册表头区域
    [self.chooseCollectionV registerClass:[HeadCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.chooseCollectionV registerClass:[FooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FooterHeader"];
    
    
    self.chooseCollectionV.backgroundColor = [UIColor clearColor];
    [self.chooseCollectionV registerClass:[ChooseTypeCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.chooseCollectionV];
    [_chooseCollectionV release];
    [flowLayout release];
    
    [self addColorChangedBlock:^{
        
        self.view.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        self.view.normalBackgroundColor = [UIColor whiteColor];
    }];
  
    
}
- (void)createHeadView
{
    // 头部区域
    UIView *headBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEADBACKVIEW)];
    headBackView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:headBackView];
    [headBackView release];
    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, headBackView.frame.size.height - 1, SCREEN_WIDTH, 1)];
//    lineV.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [headBackView addSubview:lineV];
    [lineV release];
    
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, 32)];
    titleL.text = @"感兴趣的活动类型";
    titleL.textColor = [UIColor colorWithRed:0.4 green:0.35 blue:0.35 alpha:1];
    titleL.textAlignment = NSTextAlignmentCenter;
    //    titleL.backgroundColor = [UIColor orangeColor];
    titleL.font = [UIFont boldSystemFontOfSize:18.f];
    [headBackView addSubview:titleL];
    [titleL release];
    
    self.infoL = [[UILabel alloc] initWithFrame:CGRectMake(0, titleL.frame.origin.y + titleL.frame.size.height, SCREEN_WIDTH, titleL.frame.size.height)];
    self.infoL.text = @"请选择至少3个类型哦~";
    self.infoL.textAlignment = NSTextAlignmentCenter;
    self.infoL.textColor = [UIColor colorWithRed:0.47 green:0.44 blue:0.44 alpha:1];
    self.infoL.font = [UIFont systemFontOfSize:15.f];
    //    self.infoL.backgroundColor = [UIColor orangeColor];
    [headBackView addSubview:self.infoL];
    [_infoL release];
    
    [self addColorChangedBlock:^{
        
        lineV.nightBackgroundColor = [ColorSingleton shareSingleton].cellLineColor;
        lineV.normalBackgroundColor = [ColorSingleton shareSingleton].cellLineColor;
    }];
}
#pragma mark - 点击完成发送通知
- (void)footerBtnAction
{
    
    NSMutableArray *arr = [NSMutableArray array];
    for (ChooseTypeMod *chooseMod in self.isSelectArr) {
        if ([chooseMod.isTrue isEqualToString:@"1"]) {
            [arr addObject:chooseMod];
        }
    }
    if (arr.count < 3) {
        NSLog(@"请选择至少3个类型哦");
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请选择至少3个类型哦";
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        
    } else {
      
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        
        // 发送通知 刷新订阅
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BookingRefurbish" object:arr];
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}
// 设置头部和底部区域的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (5 == indexPath.section) {
        
        FooterCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FooterHeader" forIndexPath:indexPath];
        return headView;
    } else {
        
        // 创建头部区域
        HeadCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];

        // 没网时防止程序crash
        if (self.sortKeyArr.count < indexPath.section) {
            NSLog(@"程序出错!");
            [headView setLableWithValue:@"程序出错啦~"];
            return headView;
        }

        NSInteger index = [[self.sortKeyArr objectAtIndex:indexPath.section] intValue];
        
        if (self.keyValueArr.count < index - 1) {
            NSLog(@"程序出错!");
            [headView setLableWithValue:@"程序出错啦~"];
            return headView;
        }
        
        TypeTitleModel *mod = [self.keyValueArr objectAtIndex:index - 1];
        [headView setLableWithValue:mod.titleName];
        
        
        return headView;
    }
    
    
    
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.sortKeyArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [[self.chooseDic objectForKey:[self.sortKeyArr objectAtIndex:section]] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    
    ChooseTypeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
    NSMutableArray *arr = [self.chooseDic objectForKey:[self.sortKeyArr objectAtIndex:indexPath.section]];
    TypeTitleModel *mod = [arr objectAtIndex:indexPath.row];
    
    for (ChooseTypeMod *chooseMod in self.isSelectArr) {
        if (mod.titleId == chooseMod.Id && [chooseMod.isTrue isEqualToString:@"1"]) {
            [cell setWithisOn:YES];
        } else if (mod.titleId == chooseMod.Id && [chooseMod.isTrue isEqualToString:@"0"]) {
            [cell setWithisOn:NO];
        }
    }
    
    cell.typeMod = mod;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSLog(@"--%ld %ld", indexPath.section, indexPath.row);
    ChooseTypeCollectionViewCell *cell = (ChooseTypeCollectionViewCell *)[self.chooseCollectionV cellForItemAtIndexPath:indexPath];
    
    NSMutableArray *arr = [self.chooseDic objectForKey:[self.sortKeyArr objectAtIndex:indexPath.section]];
    TypeTitleModel *mod = [arr objectAtIndex:indexPath.row];
    
    for (ChooseTypeMod *chooseMod in self.isSelectArr) {
        if (mod.titleId == chooseMod.Id && [chooseMod.isTrue isEqualToString:@"1"]) {
            chooseMod.isTrue = @"0";
            [cell setWithisOn:NO];
        } else if (mod.titleId == chooseMod.Id && [chooseMod.isTrue isEqualToString:@"0"]) {
            [cell setWithisOn:YES];
            chooseMod.isTrue = @"1";
        }
    }
}

#pragma mark - 获取标题数据
- (void)getUpdateWithURL
{
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/filterparamnew.json?source=%d&version=%d", URL_SOURCE, URL_VERSION];

    [AppTools getAFNet:url block:^(id result) {
        
        NSMutableDictionary *bigDic = result;
        NSMutableArray *categoryArr = [[bigDic objectForKey:@"data"] objectForKey:@"CategoryDoc"];
        
        NSMutableArray *moreArr = [NSMutableArray array];

        
        for (NSMutableDictionary *dic in categoryArr) {
            NSMutableArray *arr = [NSMutableArray array];
            
            if (0 == [[dic objectForKey:@"submodel"] count]) {
                

                TypeTitleModel *typeMod = [TypeTitleModel modelWithDictionary:dic];
                
                ChooseTypeMod *chooseMod = [[ChooseTypeMod alloc] init];
                chooseMod.Id = typeMod.titleId;
                chooseMod.isTrue = @"0";
                chooseMod.name = typeMod.titleName;
                [self.isSelectArr addObject:chooseMod];
                [chooseMod release];
                
                
                [moreArr addObject:typeMod];
                
                
            } else {
                for (NSMutableDictionary *subDic in [dic objectForKey:@"submodel"]) {
                    TypeTitleModel *subMod  = [TypeTitleModel modelWithDictionary:subDic];
                    
                    ChooseTypeMod *chooseMod = [[ChooseTypeMod alloc] init];
                    chooseMod.Id = subMod.titleId;
                    chooseMod.isTrue = @"0";
                    chooseMod.name = subMod.titleName;
                    [self.isSelectArr addObject:chooseMod];
                    [chooseMod release];
                    
                    [arr addObject:subMod];
                }
                [self.chooseDic setObject:arr forKey:[NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]]];
                
                TypeTitleModel *mod = [TypeTitleModel modelWithDictionary:dic];
                [self.keyValueArr addObject:mod];
  
            }
    
        }
        [self.chooseDic setObject:moreArr forKey:@"9"];

        self.sortKeyArr = [NSMutableArray arrayWithArray:self.chooseDic.allKeys];
        [self.sortKeyArr sortUsingSelector:@selector(compare:)];

        TypeTitleModel *mod = [[TypeTitleModel alloc] init];
        mod.titleId = @"6";
        mod.titleName = @"还有更多";
        [self.keyValueArr addObject:mod];
        [mod release];
    
        
        // 从数据库读取已经选择的分类
        NSMutableArray *sortArr = [[Singleton shareSingleton] selectChooseTypeWithSQL:@"SELECT * FROM chooseType"];
        
        for (ChooseTypeMod *mod in sortArr) {
            for (ChooseTypeMod *modSort in self.isSelectArr) {
                if ([mod.Id isEqualToString:modSort.Id]) {
                    modSort.isTrue = @"1";
                }
            }
        }
        

        
        [self.chooseCollectionV reloadData];

    } errorBlock:^(NSError *error) {
        [self NetworkError:^{
            [self dismissViewControllerAnimated:YES completion:^{
                
                
            }];
        }];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
